package com.ziji.rocketmq.batch;


import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.ArrayList;
import java.util.List;

/**
 * 批量消息生产者
 *
 * @author <a href="mailto:ziji.zhao@aliyun.com">ziji</a>
 * @since 2021/11/13
 */
public class BatchProducer {
    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        // 创建一个 producer，参数为 Producer Group 名称
        DefaultMQProducer producer = new DefaultMQProducer("pg");
        // 指定 NameServer 地址
        producer.setNamesrvAddr("localhost:9876");
//        // 指定要发送消息的最大大小，默认是 4M
//        // 不过，仅修改该属性是不行的，还需要同时修改 broker 加载的配置文件中的 maxMessageSize 属性
//        producer.setMaxMessageSize(4 * 1024 * 1024);

        // 开启生产者
        producer.start();

        List<Message> messages = new ArrayList<>();
        // 生产并发送 100 条消息
        for (int i=0; i<100; i++) {
            byte[] body = ("Hi," + i).getBytes();
            Message msg = new Message("batchTopic", "batchTag", body);
            msg.setKeys("key-" + i);
            messages.add(msg);
        }

        MessageListSplitter splitter = new MessageListSplitter(messages);
        while (splitter.hasNext()) {
            try {
                List<Message> subList = splitter.next();
                producer.send(subList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 关闭 producer
        producer.shutdown();
    }
}
// 7F0000011EDB18B4AAC23BDDC2F50000
// 7F0000011EF318B4AAC23BE2E9640000






































